package view;

/**
 * @author calandreli
 *
 */

/*
 Apenas o numero do Processo é editavel!

 */
import Utilitarios.TamanhoMaximoTextField;
import dao.ArquivaDAO;
import dao.ProcessoDAO;
import dao.SetorDAO;
import dao.TramitacaoDAO;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Font;
import java.beans.PropertyVetoException;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import javax.swing.table.DefaultTableModel;
import model.Arquivar;
import model.Processo;
import model.Setor;
import model.Tramitacao;
import org.netbeans.lib.awtextra.AbsoluteLayout;

//import net.sf.jasperreports.engine.JRException;
public class frameArquivar extends javax.swing.JInternalFrame {

    private DefaultTableModel modelo = new DefaultTableModel() {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    private DefaultComboBoxModel modeljcomboboxSituacao = new DefaultComboBoxModel() {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    private DefaultComboBoxModel modeljcomboboxSetor = new DefaultComboBoxModel() {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    String opcao = "";
    public int inutil;

    public frameArquivar() {
        initComponents();
        liberarCampos(true);
        montaListaSetores();
        limparcampos();

        //Tira as barras de todos os lados da janela
        ((BasicInternalFrameUI) this.getUI()).setNorthPane(null);
        ((BasicInternalFrameUI) this.getUI()).setSouthPane(null);
        ((BasicInternalFrameUI) this.getUI()).setWestPane(null);
        ((BasicInternalFrameUI) this.getUI()).setEastPane(null);

//        jtSituacao.setDocument(new TamanhoMaximoTextField(50));
        lbCodigo.setFont(new Font("Tahoma", Font.PLAIN, 11));
        lbSigla.setFont(new Font("Tahoma", Font.PLAIN, 11));

//        lbIncluir.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        lbAlterar.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        lbSalvar.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        lbCancelar.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        lbExcluir.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        lbSair.setFont(new Font("Tahoma", Font.PLAIN, 11));
        lbCodigo.setFont(new Font("Tahoma", Font.PLAIN, 11));
        lbSigla.setFont(new Font("Tahoma", Font.PLAIN, 11));

        ajusta_botoes();

        //  monta_jTUnidade();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jtMotivo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jToggleButton1 = new javax.swing.JToggleButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jCSituacao = new javax.swing.JComboBox();
        jPaneBuscar = new javax.swing.JPanel();
        jPesquisa = new javax.swing.JToggleButton();
        jtnumeroProcesso1 = new javax.swing.JTextField();
        lbCodigo = new javax.swing.JLabel();
        lbSigla2 = new javax.swing.JLabel();
        jCSetor = new javax.swing.JComboBox();
        lbSigla = new javax.swing.JLabel();
        jtData1 = new javax.swing.JFormattedTextField();
        btSair = new javax.swing.JButton();

        setClosable(true);
        setTitle("Arquivar Processo");
        setToolTipText("");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel1.setText("Arquivar Processo");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 10, 610, 30));
        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 340, 660, 10));
        getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 20, 290));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jtMotivo.setEditable(false);
        jtMotivo.setBackground(new java.awt.Color(255, 255, 255));
        jtMotivo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jtMotivo.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        jtMotivo.setToolTipText("Motivo pelo qual o processo foi arquivado");
        jtMotivo.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jtMotivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtMotivoActionPerformed(evt);
            }
        });
        jPanel3.add(jtMotivo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 490, -1));
        jtMotivo.getAccessibleContext().setAccessibleName("");
        jtMotivo.getAccessibleContext().setAccessibleDescription("Motivo do Arquivamento");

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Arquivar");
        jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 70, 60, 20));

        jToggleButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/1400699766_folder-close.png"))); // NOI18N
        jToggleButton1.setToolTipText("Confirmação para Arquivar o Processo");
        jToggleButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jToggleButton1MouseClicked(evt);
            }
        });
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jToggleButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 20, 60, 50));
        jToggleButton1.getAccessibleContext().setAccessibleName("Tramitar");

        jLabel4.setText("Situação:");
        jLabel4.setToolTipText("Situação do Processo");
        jPanel3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 60, 20));

        jLabel5.setText("Motivo:");
        jLabel5.setToolTipText("Motivo");
        jPanel3.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 60, 20));

        jCSituacao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1 - Encaminhado", "2 - Recebido" }));
        jCSituacao.setSelectedIndex(-1);
        jCSituacao.setToolTipText("Situação Atual do Processo");
        jPanel3.add(jCSituacao, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 220, -1));

        getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 150, 650, 120));

        jPaneBuscar.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPaneBuscar.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/1400784436_search_magnifying_glass_find.png"))); // NOI18N
        jPesquisa.setToolTipText("Pesquisa o Processo");
        jPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPesquisaActionPerformed(evt);
            }
        });
        jPaneBuscar.add(jPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 40, 50, -1));

        jtnumeroProcesso1.setEditable(false);
        jtnumeroProcesso1.setBackground(new java.awt.Color(255, 255, 255));
        jtnumeroProcesso1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jtnumeroProcesso1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtnumeroProcesso1.setToolTipText("Número do Processo");
        jtnumeroProcesso1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jtnumeroProcesso1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtnumeroProcesso1ActionPerformed(evt);
            }
        });
        jPaneBuscar.add(jtnumeroProcesso1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 160, -1));
        jtnumeroProcesso1.getAccessibleContext().setAccessibleDescription("Numero do Processo");

        lbCodigo.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lbCodigo.setText("Nº do Processo :");
        lbCodigo.setToolTipText("Número do Processo");
        lbCodigo.setFocusable(false);
        jPaneBuscar.add(lbCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 100, 20));

        lbSigla2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lbSigla2.setText("Data de Arquivamento:");
        lbSigla2.setToolTipText("Data de Arquivamento");
        jPaneBuscar.add(lbSigla2, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 20, 140, 20));

        jCSetor.setToolTipText("Lista dos Setores Cadastrados");
        jPaneBuscar.add(jCSetor, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 40, 220, -1));

        lbSigla.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lbSigla.setText("Setor:");
        lbSigla.setToolTipText("Setor");
        jPaneBuscar.add(lbSigla, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 20, 110, 20));

        jtData1.setBackground(new java.awt.Color(204, 204, 204));
        try {
            jtData1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtData1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtData1.setToolTipText("Data referente ao dia do Arquivamento do Processo");
        jtData1.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jtData1.setDisabledTextColor(new java.awt.Color(204, 204, 204));
        jtData1.setFocusable(false);
        jtData1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtData1ActionPerformed(evt);
            }
        });
        jtData1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtData1KeyTyped(evt);
            }
        });
        jPaneBuscar.add(jtData1, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 40, 110, -1));
        jtData1.getAccessibleContext().setAccessibleDescription("");

        getContentPane().add(jPaneBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, 650, 90));

        btSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/logout_user_login_account-3222.png"))); // NOI18N
        btSair.setToolTipText("Fechar o Arquivamento de Processo");
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });
        getContentPane().add(btSair, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 300, -1, -1));
        btSair.getAccessibleContext().setAccessibleDescription("Fechar");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtMotivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtMotivoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtMotivoActionPerformed

    private void jtnumeroProcesso1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtnumeroProcesso1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtnumeroProcesso1ActionPerformed

    private void jToggleButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jToggleButton1MouseClicked
        //       gravaRegistro();
    }//GEN-LAST:event_jToggleButton1MouseClicked

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        ArquivarProcesso();
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void jPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPesquisaActionPerformed

        try {
            if (temBanco() == true) {
                buscarProcesso();
            } else {
                JOptionPane.showMessageDialog(null, "Processo já arquivado");
                jtData1.setText("");
                jtMotivo.setText("");
                jCSetor.setSelectedIndex(-1);
                jCSituacao.setSelectedIndex(-1);
                jtnumeroProcesso1.setText("");
                jPesquisa.setSelected(false);
            }
        } catch (Exception e) {
             jPesquisa.setSelected(false);
        }        // TODO add your handling code here:
    }//GEN-LAST:event_jPesquisaActionPerformed

    private void jtData1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtData1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtData1ActionPerformed

    private void jtData1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtData1KeyTyped
        String caracteres = "0987654321";
        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_jtData1KeyTyped

    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        saiTela();
    }//GEN-LAST:event_btSairActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btSair;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox jCSetor;
    private javax.swing.JComboBox jCSituacao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPaneBuscar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JToggleButton jPesquisa;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JFormattedTextField jtData1;
    private javax.swing.JTextField jtMotivo;
    private javax.swing.JTextField jtnumeroProcesso1;
    private javax.swing.JLabel lbCodigo;
    private javax.swing.JLabel lbSigla;
    private javax.swing.JLabel lbSigla2;
    // End of variables declaration//GEN-END:variables

    public void saiTela() {
        frameArquivar.this.dispose();
    }

    public void ajustaCursor(int tipo) {
        Cursor cursor;

        if (tipo == 0) {
            cursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        } else {
            cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
        }

        setCursor(cursor);

    }

    public void ajusta_botoes() {
        if (opcao.equals("")) {

//            lbSalvar.setEnabled(false);
//            lbCancelar.setEnabled(false);
//            lbIncluir.setEnabled(true);
//            lbAlterar.setEnabled(true);
//            lbExcluir.setEnabled(true);
        } else {

//            lbSalvar.setEnabled(true);
//            lbCancelar.setEnabled(true);
//            lbIncluir.setEnabled(false);
//            lbAlterar.setEnabled(false);
//            lbExcluir.setEnabled(false);
        }
    }

    private boolean validarCampos() {

        if ((jtData1.getText() == null) || (jtData1.getText().trim().equals(""))) {
            JOptionPane.showMessageDialog(null, "O campo DATA não pode ficar em branco. Verifique!!!");
            jtData1.requestFocus();
            return false;
        } else {
            if ((jtnumeroProcesso1.getText().trim().equals("")) || (jtnumeroProcesso1.getText() == null)) {
                JOptionPane.showMessageDialog(null, "O campo NUMERO não pode ficar em branco. Verifique!!!");
                jtnumeroProcesso1.requestFocus();
                return false;
            } else {
                if ((jCSituacao.getSelectedItem() == null)) {
                    JOptionPane.showMessageDialog(null, "O campo SITUAÇÃO não pode ficar em branco. Verifique!!!");
                    jCSituacao.requestFocus();
                    return false;
                } else {
                    if ((jCSetor.getSelectedItem() == null)) {
                        JOptionPane.showMessageDialog(null, "O campo SETOR não pode ficar em branco. Verifique!!!");
                        jCSetor.requestFocus();
                        return false;
                    }
                }
            }
        }
        return true;
    }

    private void alteraRegistro() {
        liberarCampos(true);

        opcao = "alterar";

        ajusta_botoes();

//        jtSituacao.setEditable(true);
//
//        jtSituacao.requestFocus();
    }

    public void liberarCampos(boolean val) {
        jtMotivo.setEditable(val);

        jCSetor.setEditable(false);
        jCSituacao.setEditable(false);
        jtnumeroProcesso1.setEditable(val);
    }

    private void ArquivarProcesso() {
        String mens = "";
        int valor = 0;

        Arquivar a = new Arquivar();
        Calendar cal = GregorianCalendar.getInstance();
        Setor s = new Setor();
        ArquivaDAO tdao = new ArquivaDAO();
        Processo p = new Processo();
        ProcessoDAO pdao = new ProcessoDAO();
        while ((validarCampos() == true)) {
            //  p = pdao.pesquisaProcessoSingle(Integer.parseInt(jtnumeroProcesso1.getText()));
            p.setId_Processo(Integer.parseInt(jtnumeroProcesso1.getText()));
            a.setProcesso(p);
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            a.setDataArqu(c);

            a.setSituacao(jCSituacao.getSelectedItem().toString());
            a.setMotivo(jtMotivo.getText());
            tdao.incluir(a);
            valor = 1;

            //      exibePainelCadastro(false);
            JOptionPane.showMessageDialog(null, "Processo Arquivado com Sucesso!!!");
            limparcampos();
            break;
        }

    }

    private void montaListaSetores() {
        modeljcomboboxSetor.removeAllElements();
        SetorDAO as = new SetorDAO();

        ArrayList<Setor> lista3 = new ArrayList<Setor>();
        lista3 = as.findAll2();

        for (Setor a : lista3) {
            modeljcomboboxSetor.addElement(a);
        }

        jCSetor.setModel(modeljcomboboxSetor);
    }

    private void buscarProcesso() {
        ProcessoDAO pdao = new ProcessoDAO();
        Processo p = new Processo();
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date date = new Date();
        p = pdao.pesquisaProcessoSingle(Integer.parseInt(jtnumeroProcesso1.getText()));
        jCSetor.setSelectedItem(p);
        jtData1.setText(dateFormat.format(date).toString());

    }

    private void limparcampos() {
        jtnumeroProcesso1.setText(null);
        jtData1.setText(null);
        jCSetor.setSelectedIndex(-1);
        jCSituacao.setSelectedIndex(-1);
        jtMotivo.setText(null);
        jPesquisa.setSelected(false);
    }

    private boolean temBanco() {
        List<Arquivar> al = new ArrayList<Arquivar>();
        ArquivaDAO adao = new ArquivaDAO();

        al = adao.pesquisaPorProcesso(Integer.parseInt(jtnumeroProcesso1.getText()));
        if (al.isEmpty()) {
            return true;
        } else {

            return false;
        }

    }
}
